<!DOCTYPE html>
<html>
<head>
    <title>研究进度实时追踪</title>
    <style>
        .research-container {
           
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            padding: 20px;
        }
        .panel {
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 15px;
            min-height: 200px;
            background: white;
        }
        .panel-header {
            font-weight: bold;
            margin-bottom: 10px;
            padding-bottom: 5px;
            border-bottom: 2px solid #eee;
        }
        .content {
            max-height: 300px;
            overflow-y: auto;
            font-family: monospace;
        }
        .progress-bar {
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background-color: #4CAF50;
            transition: width 0.3s ease;
        }
        .message {
            padding: 5px 0;
            border-bottom: 1px solid #eee;
        }
        .timestamp {
            color: #666;
            font-size: 0.8em;
        }
        .input-panel {
            margin: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        textarea {
            width: 100%;
            min-height: 100px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
        }
        button {
            margin-top: 10px;
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="input-panel">
        <h3>研究查询输入</h3>
        <textarea id="query-input" placeholder="请输入您的研究查询..."></textarea>
        <div class="input-controls">
            <button id="submit-btn">开始研究</button>
            <button id="clear-btn">清空结果</button>
        </div>
        <div id="connection-status" style="margin-top: 10px; color: #666;"></div>
    </div>

    <div class="research-container">
        <div class="panel" id="research-panel">
            <div class="panel-header">研究进度</div>
            <div class="content" id="research-content"></div>
        </div>
    </div>

    <style>
        .input-controls {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        .message {
            margin: 8px 0;
            padding: 10px;
            border-radius: 4px;
        }
        /* 消息类型样式 */
        .plan-start, .plan-section, .plan-end { background-color: #e3f2fd; }
        .research-start, .research-end, .research-result { background-color: #f3e5f5; }
        .report-create, .report-draft, .report-finish { background-color: #e8f5e9; }
        .search, .filter, .scrape { background-color: #fff3e0; }
        .error { background-color: #ffebee; }
        .task { background-color: #f1f8e9; }
        .action { background-color: #e0f2f1; }
        .findings { background-color: #fce4ec; }
        .thought { background-color: #f3e5f5; }
        .message-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 5px;
        }
        
        .type-badge {
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 0.8em;
            background: rgba(0, 0, 0, 0.1);
            color: #333;
        }
        
        .message {
            margin: 8px 0;
            padding: 10px;
            border-radius: 4px;
        }
        
        .message-content {
            margin-top: 5px;
            white-space: pre-wrap;
        }
        
        /* 添加搜索结果的样式 */
        .search-result-item {
            margin: 8px 0;
            padding: 8px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            background-color: #f9f9f9;
        }
        .search-result-title {
            font-weight: bold;
            color: #1a0dab;
        }
        .search-result-url {
            color: #006621;
            font-size: 0.9em;
            word-break: break-all;
        }
        .search-result-description {
            margin-top: 4px;
            color: #545454;
        }
    </style>

    <script>
        const statusElement = document.getElementById('connection-status');
        let sse = null;

        document.getElementById('submit-btn').addEventListener('click', async () => {
            const query = document.getElementById('query-input').value;
            if(query.trim()) {
                statusElement.textContent = "正在发送查询...";
                
                try {
                    const response = await fetch('/api/research', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            query: query,
                            max_iterations: 5,
                            max_time_minutes: 10
                        })
                    });
                    
                    const data = await response.json();
                    statusElement.textContent = "研究任务已启动";
                    statusElement.style.color = "#4CAF50";
                    
                    // 初始化SSE连接
                    initSSE(data.client_id);
                    
                } catch (error) {
                    statusElement.textContent = `请求失败: ${error.message}`;
                    statusElement.style.color = "#F44336";
                }
            } else {
                alert('请输入有效的研究查询');
            }
        });

        function initSSE(clientId) {
            if(sse) sse.close();
            
            sse = new EventSource(`/sse/${clientId}`);
            console.log('SSE connection initialized:', clientId); // 添加调试日志
            
            sse.onmessage = (event) => {
                console.log('SSE message received:', event.data); // 添加调试日志
                try {
                    const data = JSON.parse(event.data);
                    const timestamp = new Date().toLocaleTimeString();
                    appendMessage('research-content', data.event, data.data, timestamp);
                } catch (error) {
                    console.error('Error processing SSE message:', error);
                }
            };
            
            sse.onerror = (error) => {
                console.error('SSE connection error:', error); // 添加调试日志
                statusElement.textContent = "SSE连接错误";
                statusElement.style.color = "#F44336";
            };
        
            sse.onopen = () => {
                console.log('SSE connection opened'); // 添加调试日志
                statusElement.textContent = "SSE连接已建立";
                statusElement.style.color = "#4CAF50";
            };
        }

        function appendMessage(containerId, type, content, timestamp) {
            const container = document.getElementById(containerId);
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            
            // 将消息类型转换为更友好的显示格式
            const typeDisplay = type.split('-')
                .map(word => word.charAt(0).toUpperCase() + word.slice(1))
                .join(' ');
            
            // 从content对象中提取实际消息内容
            let messageContent = content.message || content;
            
            // 特殊处理搜索结果
            if (type === 'search-result') {
                try {
                    // 尝试解析JSON格式的搜索结果
                    const results = JSON.parse(messageContent);
                    if (Array.isArray(results)) {
                        messageContent = formatSearchResults(results);
                    }
                } catch (error) {
                    console.error('解析搜索结果时出错:', error);
                }
            }
            
            messageDiv.innerHTML = `
                <div class="message-header">
                    <span class="timestamp">${timestamp}</span>
                    <span class="type-badge">${typeDisplay}</span>
                </div>
                <div class="message-content">${messageContent}</div>
            `;
            container.appendChild(messageDiv);
            container.scrollTop = container.scrollHeight;
        }

        // 添加格式化搜索结果的函数
        function formatSearchResults(results) {
            if (!results || results.length === 0) {
                return "未找到搜索结果";
            }
            
            let formattedHtml = '<div class="search-results-container">';
            
            results.forEach(item => {
                formattedHtml += `
                    <div class="search-result-item">
                        <div class="search-result-title">${escapeHtml(item.title || '无标题')}</div>
                        <div class="search-result-url">${escapeHtml(item.url || '#')}</div>
                        <div class="search-result-description">${escapeHtml(item.description || '无描述')}</div>
                    </div>
                `;
            });
            
            formattedHtml += '</div>';
            return formattedHtml;
        }
        
        // 辅助函数：转义HTML特殊字符
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 添加清空功能
        document.getElementById('clear-btn').addEventListener('click', () => {
            document.getElementById('research-content').innerHTML = '';
        });
    </script>
</body>
</html>